import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Input, 
  Select, 
  DatePicker, 
  Tag, 
  message,
  Modal,
  Descriptions,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Badge
} from 'antd';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  DownloadOutlined,
  EyeOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { confirm } = Modal;

// 日志级别枚举
enum LogLevel {
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error',
  DEBUG = 'debug'
}

// 日志类型枚举
enum LogType {
  SYSTEM = 'system',
  USER = 'user',
  SECURITY = 'security',
  OPERATION = 'operation',
  API = 'api'
}

// 日志数据接口
interface LogData {
  id: string;
  timestamp: string;
  level: LogLevel;
  type: LogType;
  module: string;
  message: string;
  details?: string;
  userId?: string;
  userName?: string;
  ip?: string;
  userAgent?: string;
  duration?: number;
  status?: 'success' | 'failed';
}

// 模拟日志数据
const mockLogs: LogData[] = [
  {
    id: '1',
    timestamp: '2024-01-20 10:30:15',
    level: LogLevel.INFO,
    type: LogType.USER,
    module: '用户管理',
    message: '用户登录成功',
    userId: 'admin',
    userName: '系统管理员',
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    status: 'success'
  },
  {
    id: '2',
    timestamp: '2024-01-20 10:25:30',
    level: LogLevel.WARN,
    type: LogType.SECURITY,
    module: '安全模块',
    message: '检测到异常登录尝试',
    details: '连续5次密码错误，账户已被临时锁定',
    ip: '192.168.1.200',
    status: 'failed'
  },
  {
    id: '3',
    timestamp: '2024-01-20 10:20:45',
    level: LogLevel.ERROR,
    type: LogType.SYSTEM,
    module: '数据库',
    message: '数据库连接超时',
    details: 'Connection timeout after 30 seconds',
    duration: 30000,
    status: 'failed'
  },
  {
    id: '4',
    timestamp: '2024-01-20 10:15:20',
    level: LogLevel.INFO,
    type: LogType.OPERATION,
    module: '子系统管理',
    message: '暖通空调系统状态更新',
    userId: 'operator1',
    userName: '操作员1',
    ip: '192.168.1.150',
    status: 'success'
  },
  {
    id: '5',
    timestamp: '2024-01-20 10:10:10',
    level: LogLevel.DEBUG,
    type: LogType.API,
    module: 'API接口',
    message: 'GET /api/subsystems/hvac',
    details: 'Response: 200 OK',
    duration: 150,
    status: 'success'
  },
  {
    id: '6',
    timestamp: '2024-01-20 10:05:35',
    level: LogLevel.ERROR,
    type: LogType.SECURITY,
    module: '权限验证',
    message: '用户权限验证失败',
    details: '用户尝试访问未授权的资源',
    userId: 'user1',
    userName: '普通用户',
    ip: '192.168.1.180',
    status: 'failed'
  }
];

const SystemLogs: React.FC = () => {
  const [logs, setLogs] = useState<LogData[]>(mockLogs);
  const [filteredLogs, setFilteredLogs] = useState<LogData[]>(mockLogs);
  const [loading, setLoading] = useState(false);
  const [selectedLog, setSelectedLog] = useState<LogData | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  
  // 搜索条件
  const [searchText, setSearchText] = useState('');
  const [selectedLevel, setSelectedLevel] = useState<LogLevel | undefined>();
  const [selectedType, setSelectedType] = useState<LogType | undefined>();
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);

  // 统计数据
  const [statistics, setStatistics] = useState({
    total: 0,
    info: 0,
    warn: 0,
    error: 0,
    debug: 0
  });

  // 计算统计数据
  useEffect(() => {
    const stats = filteredLogs.reduce((acc, log) => {
      acc.total++;
      acc[log.level]++;
      return acc;
    }, { total: 0, info: 0, warn: 0, error: 0, debug: 0 });
    
    setStatistics(stats);
  }, [filteredLogs]);

  // 过滤日志
  useEffect(() => {
    let filtered = logs;

    // 文本搜索
    if (searchText) {
      filtered = filtered.filter(log => 
        log.message.toLowerCase().includes(searchText.toLowerCase()) ||
        log.module.toLowerCase().includes(searchText.toLowerCase()) ||
        log.userName?.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    // 级别过滤
    if (selectedLevel) {
      filtered = filtered.filter(log => log.level === selectedLevel);
    }

    // 类型过滤
    if (selectedType) {
      filtered = filtered.filter(log => log.type === selectedType);
    }

    // 日期范围过滤
    if (dateRange && dateRange[0] && dateRange[1]) {
      const [start, end] = dateRange;
      filtered = filtered.filter(log => {
        const logDate = dayjs(log.timestamp);
        return logDate.isAfter(start!.startOf('day')) && logDate.isBefore(end!.endOf('day'));
      });
    }

    setFilteredLogs(filtered);
  }, [logs, searchText, selectedLevel, selectedType, dateRange]);

  // 获取日志级别标签
  const getLevelTag = (level: LogLevel) => {
    const configs = {
      [LogLevel.INFO]: { color: 'blue', icon: <InfoCircleOutlined /> },
      [LogLevel.WARN]: { color: 'orange', icon: <WarningOutlined /> },
      [LogLevel.ERROR]: { color: 'red', icon: <CloseCircleOutlined /> },
      [LogLevel.DEBUG]: { color: 'gray', icon: <InfoCircleOutlined /> }
    };
    
    const config = configs[level];
    return (
      <Tag color={config.color} icon={config.icon}>
        {level.toUpperCase()}
      </Tag>
    );
  };

  // 获取日志类型标签
  const getTypeTag = (type: LogType) => {
    const colors = {
      [LogType.SYSTEM]: 'purple',
      [LogType.USER]: 'green',
      [LogType.SECURITY]: 'red',
      [LogType.OPERATION]: 'blue',
      [LogType.API]: 'cyan'
    };
    
    const labels = {
      [LogType.SYSTEM]: '系统',
      [LogType.USER]: '用户',
      [LogType.SECURITY]: '安全',
      [LogType.OPERATION]: '操作',
      [LogType.API]: 'API'
    };
    
    return <Tag color={colors[type]}>{labels[type]}</Tag>;
  };

  // 获取状态标签
  const getStatusBadge = (status?: 'success' | 'failed') => {
    if (!status) return null;
    
    return (
      <Badge 
        status={status === 'success' ? 'success' : 'error'} 
        text={status === 'success' ? '成功' : '失败'} 
      />
    );
  };

  // 表格列配置
  const columns: ColumnsType<LogData> = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      sorter: (a, b) => dayjs(a.timestamp).unix() - dayjs(b.timestamp).unix(),
      defaultSortOrder: 'descend'
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level: LogLevel) => getLevelTag(level),
      filters: [
        { text: 'INFO', value: LogLevel.INFO },
        { text: 'WARN', value: LogLevel.WARN },
        { text: 'ERROR', value: LogLevel.ERROR },
        { text: 'DEBUG', value: LogLevel.DEBUG }
      ],
      onFilter: (value, record) => record.level === value
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: LogType) => getTypeTag(type),
      filters: [
        { text: '系统', value: LogType.SYSTEM },
        { text: '用户', value: LogType.USER },
        { text: '安全', value: LogType.SECURITY },
        { text: '操作', value: LogType.OPERATION },
        { text: 'API', value: LogType.API }
      ],
      onFilter: (value, record) => record.type === value
    },
    {
      title: '模块',
      dataIndex: 'module',
      key: 'module',
      width: 120
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: {
        showTitle: false
      },
      render: (message: string) => (
        <Tooltip title={message}>
          {message}
        </Tooltip>
      )
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
      render: (userName?: string) => userName || '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status?: 'success' | 'failed') => getStatusBadge(status)
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      )
    }
  ];

  // 查看详情
  const handleViewDetail = (log: LogData) => {
    setSelectedLog(log);
    setDetailModalVisible(true);
  };

  // 刷新日志
  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      // 模拟刷新数据
      setLogs([...mockLogs]);
      setLoading(false);
      message.success('日志刷新成功');
    }, 1000);
  };

  // 导出日志
  const handleExport = () => {
    message.success('日志导出功能开发中...');
  };

  // 清空日志
  const handleClearLogs = () => {
    confirm({
      title: '确认清空日志',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将清空所有日志记录，且无法恢复。确定要继续吗？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        setLogs([]);
        message.success('日志已清空');
      }
    });
  };

  // 重置搜索条件
  const handleReset = () => {
    setSearchText('');
    setSelectedLevel(undefined);
    setSelectedType(undefined);
    setDateRange(null);
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总日志数"
              value={statistics.total}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="错误日志"
              value={statistics.error}
              valueStyle={{ color: '#cf1322' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="警告日志"
              value={statistics.warn}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="信息日志"
              value={statistics.info}
              valueStyle={{ color: '#52c41a' }}
              prefix={<InfoCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        {/* 搜索栏 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Input
              placeholder="搜索日志内容"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择级别"
              value={selectedLevel}
              onChange={setSelectedLevel}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value={LogLevel.INFO}>INFO</Option>
              <Option value={LogLevel.WARN}>WARN</Option>
              <Option value={LogLevel.ERROR}>ERROR</Option>
              <Option value={LogLevel.DEBUG}>DEBUG</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择类型"
              value={selectedType}
              onChange={setSelectedType}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value={LogType.SYSTEM}>系统</Option>
              <Option value={LogType.USER}>用户</Option>
              <Option value={LogType.SECURITY}>安全</Option>
              <Option value={LogType.OPERATION}>操作</Option>
              <Option value={LogType.API}>API</Option>
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              value={dateRange}
              onChange={setDateRange}
              style={{ width: '100%' }}
              placeholder={['开始日期', '结束日期']}
            />
          </Col>
          <Col span={4}>
            <Space>
              <Button onClick={handleReset}>重置</Button>
              <Button type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 操作按钮 */}
        <Row justify="space-between" style={{ marginBottom: 16 }}>
          <Col>
            <Alert
              message={`共找到 ${filteredLogs.length} 条日志记录`}
              type="info"
              showIcon
            />
          </Col>
          <Col>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出
              </Button>
              <Button 
                danger 
                icon={<DeleteOutlined />} 
                onClick={handleClearLogs}
                disabled={logs.length === 0}
              >
                清空日志
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 日志表格 */}
        <Table
          columns={columns}
          dataSource={filteredLogs}
          rowKey="id"
          loading={loading}
          pagination={{
            total: filteredLogs.length,
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 详情模态框 */}
      <Modal
        title="日志详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedLog && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="时间" span={2}>
              {selectedLog.timestamp}
            </Descriptions.Item>
            <Descriptions.Item label="级别">
              {getLevelTag(selectedLog.level)}
            </Descriptions.Item>
            <Descriptions.Item label="类型">
              {getTypeTag(selectedLog.type)}
            </Descriptions.Item>
            <Descriptions.Item label="模块">
              {selectedLog.module}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {getStatusBadge(selectedLog.status)}
            </Descriptions.Item>
            <Descriptions.Item label="消息" span={2}>
              {selectedLog.message}
            </Descriptions.Item>
            {selectedLog.details && (
              <Descriptions.Item label="详细信息" span={2}>
                <pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>
                  {selectedLog.details}
                </pre>
              </Descriptions.Item>
            )}
            {selectedLog.userName && (
              <Descriptions.Item label="用户">
                {selectedLog.userName} ({selectedLog.userId})
              </Descriptions.Item>
            )}
            {selectedLog.ip && (
              <Descriptions.Item label="IP地址">
                {selectedLog.ip}
              </Descriptions.Item>
            )}
            {selectedLog.duration && (
              <Descriptions.Item label="耗时">
                {selectedLog.duration}ms
              </Descriptions.Item>
            )}
            {selectedLog.userAgent && (
              <Descriptions.Item label="用户代理" span={2}>
                {selectedLog.userAgent}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default SystemLogs;